// 导入skuModel
const Sku = require('../../models/product/sku.model');
const SkuAttr = require('../../models/product/skuAttr.model');
const SkuSaleAttr = require('../../models/product/skuSaleAttr.model');
// 导入sequelize, 处理事务
const sequelize = require('../../config/db');
// 导入响应函数
const sendResponse = require('../../utils/response');

// 获取sku列表
exports.getSkuList = async (req, res, next) => {
  try{
    // 获取分页参数
    const page = parseInt(req.params.page, 10) || 1;
    const limit = parseInt(req.params.limit, 10) || 10;
    // 计算偏移量
    const offset = (page - 1) * limit;
    // 获取sku列表
    const skuList = await Sku.findAndCountAll({
      limit,
      offset,
      order: [['id', 'DESC']],
      attributes: ['id', 'category3Id', 'spuId', 'tmId', 'price', 'skuDefaultImg', 'skuDesc', 'skuName', 'weight', 'isSale'],
      include: [{
        model: SkuAttr,
        as: 'skuAttrValueList', 
        attributes: ['id', 'skuId', 'attrId', 'valueName', 'valueId']
      },{
        model: SkuSaleAttr,
        as: 'skuSaleAttrValueList', 
        attributes: ['id', 'skuId', 'saleAttrId', 'saleAttrValueId', 'saleAttrValueName']
      }],
      distinct: true, // 确保正确计数主模型
    });

    console.log("--------获取sku列表成功--------");
    
    return sendResponse(res, {
      data: {
        records: skuList.rows,
        total: skuList.count, // 总条数
        size: limit,
        current: page,
        searchCount: true, // 搜索结果条数
        pages: Math.ceil(skuList.count / limit)
      }
    });
  } catch (error) {
    next(error);
  }
}

// 上架sku
exports.onSale = async (req, res, next) => {
  try{
    // 获取skuId
    const skuId = req.params.skuId;
    // 获取sku信息
    const sku = await Sku.findByPk(skuId);
    // 判断sku是否存在
    if (!sku) {
      return sendResponse(res, {
        code: 404,
        message: 'sku不存在'
      });
    }
    // console.log(sku.isSale);
    
    // 判断sku是否已上架
    if (sku.isSale === true) {
      return sendResponse(res, {
        code: 400,
        message: 'sku已上架'
      });
    }
    // 上架sku
    await sku.update({
      isSale: true
    });
    // 返回响应
    return sendResponse(res, {
      message: '上架成功'
    });
  } catch (error) {
    next(error);
  }
}

// 下架sku
exports.cancelSale = async (req, res, next) => {
  try{
    // 获取skuId
    const skuId = req.params.skuId;
    // 获取sku信息
    const sku = await Sku.findByPk(skuId);
    // 判断sku是否存在
    if (!sku) {
      return sendResponse(res, {
        code: 404,
        message: 'sku不存在'
      });
    }
    // console.log(sku.isSale);

    // 判断sku是否已下架
    if (sku.isSale === false) {
      return sendResponse(res, {
        code: 400,
        message: 'sku已下架'
      });
    }
    // 下架sku
    await sku.update({
      isSale: false
    });
    // 返回响应
    return sendResponse(res, {
      message: '下架成功'
    });
  } catch (error) {
    next(error);
  }
}

// 查看sku详情
exports.getSkuDetail = async (req, res, next) => {
  try{
    // 获取skuId
    const skuId = req.params.skuId;
    // 获取sku信息
    const sku = await Sku.findByPk(skuId, {
      include: [{
        model: SkuAttr,
        as: 'skuAttrValueList', 
        attributes: ['id', 'skuId', 'attrId', 'valueName', 'valueId']
      },{
        model: SkuSaleAttr,
        as: 'skuSaleAttrValueList', 
        attributes: ['id', 'skuId', 'saleAttrId', 'saleAttrValueId', 'saleAttrValueName']
      }]
    });
    // TODO 缺少sku图片列表
    // 返回响应
    return sendResponse(res, {
      data: sku
    });
  } catch (error) {
    next(error);
  }
}

// 删除sku
exports.deleteSku = async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try{
    // 获取skuId
    const skuId = req.params.skuId;
    // 获取sku信息
    const sku = await Sku.findByPk(skuId);
    // 判断sku是否存在
    if (!sku) {
      return sendResponse(res, {
        code: 404,
        message: 'sku不存在'
      });
    }
    // 删除sku
    await Sku.destroy({
      where: {
        id: skuId
      },
      transaction
    });
    // 删除sku属性
    await SkuAttr.destroy({
      where: {
        skuId
      },
      transaction
    });
    // 删除sku销售属性
    await SkuSaleAttr.destroy({
      where: {
        skuId
      },
      transaction
    });
    // 提交事务
    await transaction.commit();
    // 返回响应
    return sendResponse(res, {
      message: '删除成功'
    });
  } catch (error) {
    await transaction.rollback();
    next(error);
  }
}
